package ch.bfh.medinfo.javafx.dice.implementation;

import java.util.Random;

import ch.bfh.medinfo.javafx.dice.definition.Dice;

/**
 * Implements a dice which is using the inner mechanism of Java to have a 'fair'
 * randomness for a simple dice game. Please note: This implementation is not
 * suitable for security related things such as games involving money...
 * 
 * @author reto
 * 
 */
public class FairDice implements Dice {
	private static final Random random;
	private int minValue;
	private int maxValue;
	private int actualValue;

	/**
	 * Instanciation of randomization. This is done only once, when the class is
	 * loaded via standard class loader.
	 */
	static {
		random = new Random();
	}

	/**
	 * 
	 * @param minValue
	 * @param maxValue
	 */
	public FairDice(int minValue, int maxValue) {
		// Verify if values make sense
		if (minValue >= maxValue)
			throw new IllegalArgumentException();

		// Assign values
		this.maxValue = maxValue;
		this.minValue = minValue;

		initialize();
	}

	protected void initialize() {
		// Play a first time, in order to initialize acutalValue
		play();
	}

	@Override
	public void play() {
		// Calculate the range between min and max
		int range = Math.abs(this.maxValue - this.minValue);

		// get a random value within the range (careful: random(3) -> 0,1,2 but
		// never 3)
		int randomValueInRange = random.nextInt(range + 1);

		this.actualValue = this.minValue + randomValueInRange;
	}

	@Override
	public int getActualValue() {
		return this.actualValue;
	}

	@Override
	public int getMinValue() {
		return this.minValue;
	}

	@Override
	public int getMaxValue() {
		return this.maxValue;
	}

}
